<template>

  <el-card>
    <el-form :model="usersForm" :rules="rules" ref="formRef">
      <el-form-item label="姓名" prop="name">
        <el-input
            placeholder="请您输入姓名"
            v-model="usersForm.name"
        ></el-input>
      </el-form-item>
      <el-form-item label="电话" prop="phone">
        <el-input
            placeholder="请您输电话"
            v-model="usersForm.phone"
        ></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
            type="email"
            placeholder="请您输邮箱"
            v-model="usersForm.email"
        ></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input
            placeholder="请您输地址"
            v-model="usersForm.address"
        ></el-input>
      </el-form-item>
      <el-form-item label="账号" prop="username">
        <el-input
            :disabled="true"
            v-model="usersForm.username"
        ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
            v-model="usersForm.password"
            style="width: 240px"
            type="password"
            show-password
        ></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-switch
            v-model="sex"
            inline-prompt
            active-text="男"
            inactive-text="女"
        />
      </el-form-item>
      <el-form-item label="余额" prop="accountBalance">
        <el-text class="mx-1" type="primary">{{ usersForm.accountBalance}}</el-text>
      </el-form-item>
      <el-form-item label="头像" prop="avatar">
        <el-upload
            class="upload-demo"
            :show-file-list="false"
            accept=".png,.jpg,.jpeg,.gif"
            drag
            :before-upload="handleBeforeUpload"
            :http-request="handleCustomUploadAvatar"
            multiple
        >
          <img style="width: 200px; height: 200px;" v-if="usersForm.avatar"
               :src="usersForm.avatar" class="avatar" alt="图片"/>
          <el-icon v-else class="avatar-uploader-icon">
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
  </el-card>


</template>

<script setup lang="ts">
import {ref, reactive, onMounted, nextTick} from 'vue'
import {ElFormItem, ElMessage} from 'element-plus'
import {Plus} from "@element-plus/icons-vue";
import {apiGet, apiPost} from "@/utils/api.ts";
// 表单数据
let usersForm = reactive(
    {
      userId: 0,
      name: '',
      phone: '',
      email: '',
      address: '',
      username: '',
      password: '',
      gender: '男',
      accountBalance: 0.00,
      avatar: '',
    })
//获取form组件实例
let formRef = ref<any>()
let sex = ref<boolean>(false);
//获取用户信息
let getOneById = async () => {
  //获取表单数据
  let {data} = await apiGet('/users/getById')
  data.gender === '男' ? sex.value = true : sex.value = false;
  Object.assign(usersForm, {
    ...data
  })
  //清除上一次的错误的提示信息
  await nextTick(() => {
    formRef.value.clearValidate()
  })
}

//保存按钮的回调
const save = async () => {
  //点击保存按钮的时候,务必需要保证表单全部复合条件在去发请求
  await formRef.value.validate()
  if (!sex.value) {
    usersForm.gender = '女';
  } else {
    usersForm.gender = '男';
  }
  await apiPost('/users/edit', {...usersForm})
  await getOneById()
}
//上传文件之前做的一些判断
const handleBeforeUpload = (file) => {
  // 检查文件类型 只能上传.png,.jpg,.jpeg,.gif
  const isExcel = file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/gif';
  if (!isExcel) {
    ElMessage.error('上传文件只能是.png,.jpg,.jpeg,.gif 格式!');
    return false;
  }

  //上传文件大小不能超过20M
  const isLt20M = file.size / 1024 / 1024 < 20;
  if (!isLt20M) {
    ElMessage.error('上传文件大小不能超过 20MB!');
    return false;
  }
  return isExcel && isLt20M;
};
const handleCustomUploadAvatar = async (option) => {
  const formData = new FormData();
  formData.append('file', option.file);
  let {msg} = await apiPost('/upload/img', formData, {headers: {'Content-Type': 'multipart/form-data'}});
  usersForm.avatar = msg;
};
const validatorName = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入用户名'));
  } else {
    callback();
  }
}
const validatorEmail = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入邮箱'));
  } else {
    if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(value)) {
      callback(new Error('请输入正确的邮箱'));
    }
    callback();
  }
}
const validatorAccount = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'));
  } else {
    callback();
  }
}
//表单校验的规则对象
const rules = {
  name: [{required: true, trigger: 'blur', validator: validatorName}],
  email: [{required: true, trigger: 'blur', validator: validatorEmail}],
  username: [{required: true, trigger: 'blur', validator: validatorAccount}],
}


//组件挂载完毕
onMounted(() => {
  getOneById()
})
</script>

<style scoped>
</style>
